import redis

"""
将学生表保存到redis中
key的设计：student:id
value设计，使用散列作为value,每个字段作为散列的一个元素

"""

# 1、创建redis连接
con = redis.Redis(host="master", port=6379, decode_responses=True, encoding="Utf-8")

# 2、读取学生表
with open("../../data/students.txt", mode="r", encoding="UTF-8") as file:
    students = [line.rstrip() for line in file.readlines()]

# 3、循环将数据保存到redis中
for student in students:
    # 按照逗号切分数据
    split = student.split(",")

    id = split[0]
    name = split[1]
    age = split[2]
    sex = split[3]
    clazz = split[4]

    # 构建key
    key = f"student:{id}"

    # 一次存入多个元素
    con.hset(key, mapping={"name": name, "age": age, "sex": sex, "clazz": clazz})

# 关闭连接
con.close()
